import { sqlite } from "./index.js";

const tableName = 'sys_user'

const fields = `"worker_id" INTEGER NOT NULL,"worker_name" text not null,"worker_no" INTEGER, "chat_account" text,
			"worker_type" INTEGER not null,"address" text,"age" text,"birth_date" text,"depart_id" INTEGER,"entry_date" text,
			"img_url" text,"is_delete" text,"new_depart_name" text,"phone" text,"role_id" INTEGER,"status" text,"token" text,"sex" text
		`
/**
* @worker_id Int
* @worker_name String
* @worker_no Int
* @worker_type Int
* @address String
* @age Int
* @birth_date String
* @depart_id Int
* @entry_date String
* @img_url String
* @is_delete Int
* @new_depart_name String
* @phone String
* @role_id Int
* @sex Int
* @status Int
* @token String
* @chat_account String
**/
	 
export const SysUser = {
	/**
	 * 初始化USER
	 **/
	init: function(){
		return new Promise(async(resolve, reject) => {
			if(!sqlite.isOpen()){
				await sqlite.openDb();
			}
			sqlite.isTable(tableName).then(res => {
				if(res) {
					const sql = `select * from ${tableName};`
					sqlite.selectBySQL(sql).then(user => {
						resolve(user);
					})
				}else {
					sqlite.createTab(tableName, fields);
					resolve([]); 
				}
			}).catch(err => {
				console.log('读取表是否存在失败', err);
				reject(err); 
			})
		})
	},
	/**
	 * 查询用户信息
	 **/
	selectAll: function() {
		return sqlite.selectBySQL(`select * from ${tableName};`);
	},
	/**
	 * 添加用户信息
	 **/
	insert: function(data){
		return sqlite.addTabItem(tableName, data);
	},
	/**
	 * 修改用户信息
	 **/
	updateById: function(id, key, keyValue) {
		let sql = `update ${tableName} set ${key} = '${keyValue}' where worker_id = ${id}`;
		return sqlite.updateBySQL(sql);
	},
	/**
	 * 删除用户信息
	 **/
	deleteById: function(id){
		return sqlite.deleteInformationType(tableName, {'worker_id': id});
	},
}
	 